package com.bbg.amyam.web.mvc.security;

import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.bbg.amyam.domain.model.Profile;

@Service("amyamUserSecurityService")
public class AmyamUserSecurityService implements AmyamUserDetailService {

	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {
		List<Profile> profiles = Profile.findProfilesByEmailEquals(username)
				.getResultList();
		if (profiles.size() > 0) {
			Profile profile = profiles.get(0);
			ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder
					.currentRequestAttributes();
			HttpServletRequest request = attr.getRequest();
			
			String schoolShortName=(String)request.getParameter("_uname");

			if (schoolShortName != null) {
				if (!StringUtils.isBlank(schoolShortName)) {
					AmyamUserDetail userDetail = new AmyamUserDetail(profile,
							schoolShortName);
					return userDetail;
				}
			}

		}
		return null;
	}

}
